package com.lw.leetcode.arr.c;

import com.lw.test.util.Utils;

/**
 * Created with IntelliJ IDEA.
 * 6207. 统计定界子数组的数目
 *
 * @author liw
 * @version 1.0
 * @date 2022/10/17 10:01
 */
public class CountSubarrays {

    public static void main(String[] args) {
        CountSubarrays test = new CountSubarrays();

        // 2
//        int[] arr = {1, 3, 5, 2, 7, 5};
//        int minK = 1;
//        int maxK = 5;

        // 10
//        int[] arr = {1, 1, 1, 1};
//        int minK = 1;
//        int maxK = 1;

        //
        int[] arr = Utils.getArr(100000, 1, 1000);
        int minK = arr[1356];
        int maxK = 0;
        for (int i : arr) {
            if (i > minK) {
                maxK = i;
                break;
            }
        }
        System.out.println(minK);
        System.out.println(maxK);

        long l = test.countSubarrays(arr, minK, maxK);
        System.out.println(l);

    }

    public long countSubarrays(int[] nums, int minK, int maxK) {
        int length = nums.length;
        int a = -1;
        int b = -1;
        int st = 0;
        long sum = 0;
        for (int i = 0; i < length; i++) {
            int v = nums[i];
            if (v < minK || v > maxK) {
                a = -1;
                b = -1;
                st = i + 1;
                continue;
            }
            if (minK == v) {
                a = i;
            }
            if (maxK == v) {
                b = i;
            }
            int m = Math.min(a, b);
            if (m != -1) {
                sum += (m - st + 1);
            }
        }
        return sum;
    }

}
